package com.ruoyi.common.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.config.WechatConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: liuweicheng
 * @Date: 2019-09-13 16:20
 */
@SuppressWarnings("all")
@Component
public class AliOSSUtils {

    private final static String accessKeyId = WechatConfig.OSS.accessKeyId;
    private final static String accessKeySecret = WechatConfig.OSS.accessKeySecret;
    private final static String bucketName = WechatConfig.OSS.bucketName;
    private final static String url = WechatConfig.OSS.url;
    private static String endpoint = WechatConfig.OSS.endpoint;
    private static String bucketUrl = WechatConfig.OSS.bucketUrl;
    private static String env;//当前激活的配置文件

    public static Map<String, Object> uploadFileImg(String fileName, MultipartFile param) throws IOException {
        setEnv();
        fileName = "upload/" + fileName;
        Map<String, Object> map = new HashMap<>();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, param.getInputStream());
        map.put("imgUrl", "/" + fileName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return map;
    }

    public static Map<String, Object> uploadFileImg(String fileName, File file) throws IOException {
        setEnv();
        fileName = "upload/" + fileName;
        Map<String, Object> map = new HashMap<>();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, file);
        map.put("imgUrl", "/" + fileName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return map;
    }

    public static Map<String, Object> uploadFileImgUrl(String fileUrl, File file) throws IOException {
        setEnv();
        Map<String, Object> map = new HashMap<>();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileUrl, file);
        map.put("imgUrl", "/" + fileUrl);
        // 关闭OSSClient。
        ossClient.shutdown();
        return map;
    }

    private static void setEnv() {

    }

    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        AliOSSUtils.env = env;
    }
}
